package com.jic.market.controller.manage;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.market.api.manage.PatchGrouponProductManageApi;
import com.jic.market.bo.GrouponProductExcelBO;
import com.jic.market.common.constant.CommonConst;
import com.jic.market.common.constant.PatchGrouponStockLmtConstant;
import com.jic.market.common.enums.DeleteFlagEnum;
import com.jic.market.common.enums.MutexFlagEnum;
import com.jic.market.common.enums.TypeOfProductEnum;
import com.jic.market.common.util.ListUtils;
import com.jic.market.entity.*;
import com.jic.market.impl.excel.ExcelListener;
import com.jic.market.impl.excel.ExcelListenerData;
import com.jic.market.orm.Pagination;
import com.jic.market.request.*;
import com.jic.market.request.manager.patchgroup.PatchGrouponProductSkuCountRequest;
import com.jic.market.request.manager.presell.PresellProductIsNullRequest;
import com.jic.market.response.*;
import com.jic.market.service.PatchGroupMerchantProductService;
import com.jic.market.service.PatchGrouponStockLmtService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 拼团商品
 *
 * @author guohuayong
 * @date 2020/2/24 17:26
 **/
@Api(tags = {"拼团商品"})
@Slf4j
@RestController
@RequestMapping("/product/groupon")
public class PatchGrouponProductManageController implements PatchGrouponProductManageApi {
    @Autowired
    private PatchGroupMerchantProductService gmpService;
    @Autowired
    private PatchGrouponStockLmtService stockLmtEntityService;


    @RequestMapping("/saveBatch")
    @Override
    public RestResult<Integer> saveBatch(@RequestBody PatchGroupProductSaveListRequest ppr) {
        Integer ret = gmpService.saveBatch(ppr.getProductPromotionList());


        // 添加促销商品的限制项
        for(PatchGouponProductRequest promotionProduct : ppr.getProductPromotionList()){
            PatchGrouponStockLmtEntity limitEntity = new PatchGrouponStockLmtEntity();
            PatchGrouponStockLmtEntity dbEntity = stockLmtEntityService.getEntityByPromotionIdAndMpId(
                    promotionProduct.getPromotionId(), promotionProduct.getMpId());
            if(dbEntity!=null){
                continue;
            }
            limitEntity.setRefPatchGrouponTheme(promotionProduct.getPromotionId());
            limitEntity.setMerchantId(promotionProduct.getMerchantId());
            limitEntity.setMerchantProductId(promotionProduct.getMpId());
            limitEntity.setMpCode(promotionProduct.getMpCode());
            limitEntity.setTypeOfProduct(promotionProduct.getTypeOfProduct());
//            limitEntity.setStoreId(promotionProduct.getStoreId());
            limitEntity.setStoreName(promotionProduct.getStoreName());
            limitEntity.setMerchantProductName(promotionProduct.getMpName());
            limitEntity.setRuleType(PatchGrouponStockLmtConstant.RuleType.SHARE.getCode());

            stockLmtEntityService.addPromotionLimitRule(limitEntity);
        }

        return RestResult.success(ret);
    }

    @ApiOperation(value = "批量保存V2")
    @PostMapping("/saveBatchV2")
    @Override
    public RestResult<Integer> saveBatchV2(@RequestBody PatchGroupProductSaveV2ListRequest listRequest) {

        // 保存待促销商品
        List<PatchGroupProductSaveV2Request> productPromotionList = listRequest.getProductPromotionList();
        Integer count = gmpService.saveBatchV2(productPromotionList);
        return RestResult.success(count);
    }


    @PostMapping("/addAllProduct")
    @Override
    public RestResult<Integer> addAllProduct(@RequestBody PatchGroupProductAddAllProductRequest addAllProductRequest) {

        Integer count = gmpService.addAllProduct(addAllProductRequest);
        return RestResult.success(count);
    }

    @PostMapping("/save")
    @Override
    public RestResult<Integer> save(@RequestBody PatchGouponProductRequest request) {
        Integer ret = gmpService.save(request);
        return RestResult.success(ret);
    }

    @RequestMapping("/update")
    @Override
    public RestResult<Integer> update(@RequestBody PatchGouponProductRequest pgpr) {
        Integer ret =  stockLmtEntityService.updateByPromotionIdMpId(pgpr);

        return RestResult.success(ret);
    }


    @PostMapping("/updateStockLimit")
    @Override
    public RestResult<Integer> updateStockLimit(@RequestBody PatchGrouponUpdateStockLimitRequest request) {
        Integer ret =  stockLmtEntityService.updateLimitById(request);
        return RestResult.success(ret);
    }

    @RequestMapping("/getProductList")
    @Override
    public RestResult<PageResult<PatchGroupProductResponse>> getPromotionProductList(
            @RequestBody PromotionProductQueryListRequest ppqlRequest) {
        PatchGrouponMpEntity condition =new PatchGrouponMpEntity();
        BeanUtils.copyProperties(ppqlRequest,condition);
        Pagination pagination =Pagination.build(ppqlRequest.getStart(), ppqlRequest.getLimit());

        condition.setDeleteFlag(CommonConst.DeleteEnum.NOT_DELETE.getCode());

        List<PatchGrouponMpEntity> productList = gmpService.findOfPage(condition, pagination);
        Integer count = gmpService.countOfPage(condition);
        List<PatchGroupProductResponse> patchGroupProductResponses = ListUtils.entityListToModelList(productList, PatchGroupProductResponse.class);
        if(patchGroupProductResponses !=null && patchGroupProductResponses.size() !=0){
            for (PatchGroupProductResponse groupProduct : patchGroupProductResponses) {
                PatchGrouponStockLmtEntity limitEntity =
                        stockLmtEntityService.getEntityByPromotionIdAndMpId(groupProduct.getPromotionId(), groupProduct.getMpId());
                groupProduct.setGrouponPrice(limitEntity.getGrouponPrice());
                groupProduct.setIndividualLimit(limitEntity.getIndividualLimit());
                groupProduct.setChannelStoreLimit(limitEntity.getChannelStoreLimit());
                groupProduct.setChannelMerchantLimit(limitEntity.getChannelMerchantLimit());
            }
        }
        PageResult<PatchGroupProductResponse> pageResult =new PageResult<>();
        pageResult.setRows(patchGroupProductResponses);
        pageResult.setTotal(count);
        return RestResult.success(pageResult);
    }

    @ApiOperation(value = "获取促销商品列表V2")
    @PostMapping("/getProductListV2")
    @Override
    public RestResult<PageResult<PatchGroupProductV2Response>> getPromotionProductListV2(@RequestBody PatchGroupPromotionProductQueryListV2Request ppqlRequest) {
        return RestResult.success(gmpService.getPromotionProductListV2(ppqlRequest));
    }

    @ApiOperation(value = "商品Sku统计")
    @PostMapping("/skuCount")
    public RestResult<Long> skuCount(@RequestBody PatchGrouponProductSkuCountRequest request) {
        Long aLong = gmpService.skuCount(request);
        return RestResult.success(aLong);
    }

    @PostMapping("/deleteProductBatch")
    @Override
    public RestResult deleteProductBatch(@RequestBody DeletePatchGrouponProductBatchRequest request) {
        gmpService.deleteProductBatch(request.getMainProductList());
        return RestResult.success(null);
    }

    @PostMapping("/deleteProductBatchV2")
    @Override
    public RestResult deleteProductBatchV2(@RequestBody DeletePatchGrouponProductBatchV2Request request) {
        Integer count = gmpService.deleteProductBatchV2(request.getMainProductList());
        return RestResult.success(count);
    }


    @RequestMapping("/deleteProduct")
    @Override
    public RestResult<Integer> deleteProduct(@RequestBody PatchGouponProductRequest request) {
        Integer ret= gmpService.deleteProduct(request.getPromotionId(), request.getMpId());
        return RestResult.success(ret);
    }

    @PostMapping("/deleteProductV2")
    @Override
    public RestResult deleteProductV2(@RequestBody PatchGouponProductDeleteV2Request request) {
        Integer count = gmpService.deleteProductV2(request.getPatchGrouponMpId());
        return RestResult.success(count);
    }

    /**
     * 导入数据
     * @param file
     */
    @ApiOperation(value= "导入数据", notes= "导入数据")
    @PostMapping(value = "/importExcel")
    @Override
    public RestResult<String> importExcel(
            @RequestParam("file") MultipartFile file, @RequestParam("promotionId") Long promotionId) {

        try{
            ExcelListenerData elData = gmpService.importMpExcel(file, promotionId, new GrouponProductExcelBO());
            if (elData == null) {
                log.error("插入数据库失败!");
                return RestResult.error("9999","插入数据库失败!");
            }
            log.info("---{}---",JSON.toJSON(elData));
        }catch (Exception e) {
            log.error("-----导入excel促销商品异常---",e);
        }
        return RestResult.success("成功");
    }

}
